package com.ruoyi.project.rate.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.rate.Constants;
import com.ruoyi.project.rate.ExcelUtil;
import com.ruoyi.project.rate.RuleComparator;
import com.ruoyi.project.rate.Utils;
import com.ruoyi.project.rate.domain.KhzDept;
import com.ruoyi.project.rate.domain.Result;
import com.ruoyi.project.rate.domain.Rule;
import com.ruoyi.project.rate.service.KhzDeptService;
import com.ruoyi.project.rate.service.RuleService;
import com.ruoyi.project.system.dept.domain.Dept;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.dict.service.IDictDataService;

@Controller
@RequestMapping("/rate/rule")
public class RuleController extends BaseController {
	@Autowired
	private RuleService ruleService;
	@Autowired
	private IDeptService deptService;
	@Autowired
	KhzDeptService khzDeptService;
	@Autowired
	private IDictDataService dictDataService;

	@RequestMapping("/rule")
	public String rule(Rule rule, ModelMap mmap) {
		List<Dept> deptList = new ArrayList<Dept>();
		deptList.addAll(Utils.level2DeptList());

		mmap.put("rule", rule);
		mmap.put("deptList", deptList);

		return "rate/ruleList";
	}
	
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Rule rule) {
//		startPage();
		List<Rule> list;
		list = this.ruleService.findList(rule);
		list.sort(new RuleComparator());
//		if (StringUtils.isAnyBlank(rule.getKhz(), rule.getType())) {
//			list = new ArrayList<Rule>();
//		} else {
//			list = this.ruleService.findList(rule);
//		}
		return getDataTable(list);
	}
	
	/**
	 * 导出考核细则
	 * @param r
	 * @return
	 */
	@RequestMapping("/export")
	@ResponseBody
	public AjaxResult export(Result r) {
		
		
		List<String> khzList = Arrays.asList("001", "002", "003", "004");
		List<String> khTypeList = Arrays.asList(Constants.KH_TYPE_ZHU, Constants.KH_TYPE_DU);
		
		Workbook wb = null;
		OutputStream out = null;
		String filename = "考核细则表.xlsx";
		try {
			wb = new SXSSFWorkbook(500);
			Sheet sheet;
			Row row;
			Cell cell;
			int sheetIndex = 0;
			int rowIndex = 0;
			int colIndex = 0;
			
			CellStyle horizontalTextWithSongti11 = Utils.styleOfSongti11Horizontal(wb);
			CellStyle baseStype = Utils.baseBorderStyle(wb);
			
			// 每个考核组、每个考核类型一个sheet begin
			for (String khz : khzList) {
				for (String khType : khTypeList) {
					Rule _rule = new Rule();
					_rule.setKhz(khz);
					_rule.setType(khType);
					List<Rule> ruleList = this.ruleService.findList(_rule);
					ruleList.sort(new RuleComparator());
					
					String khzName = this.dictDataService.selectDictLabel(Constants.KHZ, khz);
					String khTypeName = this.dictDataService.selectDictLabel(Constants.KH_TYPE, khType);
					sheet = wb.createSheet();
					wb.setSheetName(sheetIndex++,
							StringUtils.defaultIfBlank(khzName, "") + "_" + StringUtils.defaultIfBlank(khTypeName, ""));
					rowIndex = 0;
					
					// 表头 begin
					row = sheet.createRow(rowIndex++);
					row.setHeight((short)(40 * 20));
					colIndex = 0;
					cell = row.createCell(colIndex++);
					cell.setCellValue("考核类别");
					cell.setCellStyle(horizontalTextWithSongti11);
					sheet.setColumnWidth(colIndex - 1, 10 * 256);
					cell = row.createCell(colIndex++);
					cell.setCellValue("考核单位");
					cell.setCellStyle(horizontalTextWithSongti11);
					sheet.setColumnWidth(colIndex - 1, 10 * 256);
					cell = row.createCell(colIndex++);
					cell.setCellValue("考核项目");
					cell.setCellStyle(horizontalTextWithSongti11);
					sheet.setColumnWidth(colIndex - 1, 35 * 256);
					cell = row.createCell(colIndex++);
					cell.setCellValue("考核序号");
					cell.setCellStyle(horizontalTextWithSongti11);
					sheet.setColumnWidth(colIndex - 1, 9 * 256);
					cell = row.createCell(colIndex++);
					cell.setCellValue("分值");
					cell.setCellStyle(horizontalTextWithSongti11);
					sheet.setColumnWidth(colIndex - 1, 10 * 256);
					cell = row.createCell(colIndex++);
					cell.setCellValue("考核内容及标准");
					cell.setCellStyle(horizontalTextWithSongti11);
					sheet.setColumnWidth(colIndex - 1, 35 * 256);
					cell = row.createCell(colIndex++);
					cell.setCellValue("考核方式");
					cell.setCellStyle(horizontalTextWithSongti11);
					sheet.setColumnWidth(colIndex - 1, 25 * 256);
					// 表头 end
					
					for (Rule rule : ruleList) {
						row = sheet.createRow(rowIndex++);
						row.setHeight((short)(40 * 20));
						colIndex = 0;
						cell = row.createCell(colIndex++);
						cell.setCellValue(rule.getLb());
						cell.setCellStyle(baseStype);
						cell = row.createCell(colIndex++);
						cell.setCellValue(rule.getDept().getDeptName());
						cell.setCellStyle(baseStype);
						cell = row.createCell(colIndex++);
						cell.setCellValue(rule.getXm());
						cell.setCellStyle(baseStype);
						cell = row.createCell(colIndex++);
						cell.setCellValue(rule.getXh());
						cell.setCellStyle(baseStype);
						cell = row.createCell(colIndex++);
						cell.setCellValue(rule.getFz());
						cell.setCellStyle(baseStype);
						cell = row.createCell(colIndex++);
						cell.setCellValue(rule.getNr());
						cell.setCellStyle(baseStype);
						cell = row.createCell(colIndex++);
						cell.setCellValue(rule.getFs());
						cell.setCellStyle(baseStype);
					}
				}
			}
			
			String filepath = Utils.getExportAbsoluteFile(filename);
			File file = new File(filepath);
			if (file.exists() && file.isFile()) {
				file.delete();
			}
			out = new FileOutputStream(filepath);
			wb.write(out);
			return AjaxResult.success(filename);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("导出Excel失败，请联系网站管理员！");
		} finally {
			IOUtils.closeQuietly(wb);
			IOUtils.closeQuietly(out);
		}
	}
	
	@RequestMapping("/edit")
	public String edit(Rule rule, ModelMap mmap) {
		Rule r = this.ruleService.get(rule);
		if (r == null) {
			throw new RuntimeException("找不到对应的数据！");
		}
		r.setPageFlag(rule.getPageFlag());

		mmap.put("rule", r);
		mmap.put("deptList", Utils.level2DeptList());
		
		return "rate/ruleForm";
	}
	
	@PostMapping("/save")
	@ResponseBody
	public AjaxResult save(Rule rule) {
		String pageFlag = rule.getPageFlag();
		if (!StringUtils.equalsAny(pageFlag, "ADD", "EDIT")) {
			throw new RuntimeException("error pageFlag.");
		}
		
		/*
		 * if (rule.getDept() == null || rule.getDept().getDeptId() == null ||
		 * rule.getDept().getDeptId() == 0L) { throw new
		 * RuntimeException("please select dept."); }
		 */
		this.ruleService.save(rule);

		return AjaxResult.success("保存成功！");
	}
	
	@SuppressWarnings("unused")
	@PostMapping("/importRule")
	@ResponseBody
	public AjaxResult importRule(String khz, String type, MultipartFile file) throws Exception {
		if (StringUtils.isBlank(khz)) {
			return AjaxResult.error("blank khz.");
		}
		if (StringUtils.isBlank(type)) {
			return AjaxResult.error("blank type.");
		}
		if (file == null || file.getInputStream() == null) {
			return AjaxResult.error("提交文件为空。");
		}
		String originFilename = file.getOriginalFilename();
		if (StringUtils.isBlank(originFilename)) {
			return AjaxResult.error("提交文件格式不正确，建议使用系统模板填写。");
		}

		List<Rule> ruleList = new ExcelUtil().importRule(file.getInputStream());
		if (ruleList == null || ruleList.size() == 0) {
			return AjaxResult.error("提交文件无数据记录。");
		}
		List<Dept> deptList = this.deptService.selectDeptList(new Dept());
		Map<String, Dept> deptMap = new HashMap<String, Dept>();
		for (Dept d : deptList) {
			deptMap.put(d.getDeptName(), d);
		}
		
		// 根据考核组查询部门信息
		KhzDept khzDept = new KhzDept();
		khzDept.setKhz(khz);
		List<KhzDept> khzDeptList = this.khzDeptService.findList(khzDept);
		Map<String, Dept> khzDeptMap = new HashMap<>();
		if (khzDeptList != null) {
			for (KhzDept kd : khzDeptList) {
				khzDeptMap.put(kd.getDept().getDeptName(), kd.getDept());
			}
		}

		List<Rule> importList = new ArrayList<Rule>();
		String lastXm = null;
		String lastFz = null;
		String lastFs = null;
		String lastXh = null;
		int index = 1;
		
		StringBuilder errorMsg = new StringBuilder();
		for (Rule r : ruleList) {
			System.out.println("process rule " + (index++));
			/**
			if (StringUtils.isNotBlank(r.getXm())) {
				lastXm = r.getXm();
			} else {
				r.setXm(lastXm);
			}
			
			if (StringUtils.isNotBlank(r.getFz())) {
				lastFz = r.getFz();
			} else {
				r.setFz(lastFz);
			}
			
			if (StringUtils.isNotBlank(r.getFs())) {
				lastFs = r.getFs();
			} else {
				r.setFs(lastFs);
			}
			
			if (StringUtils.isNotBlank(r.getXh())) {
				lastXh = r.getXh();
			} else {
				r.setXh(lastXh);
			}
			**/
			
			if (StringUtils.isBlank(r.getLb())) {
//				errorMsg.append("第【" + index + "】行类别为空；");
//				continue;
			}
			if (StringUtils.isBlank(r.getXm())) {
				errorMsg.append("第【" + index + "】行项目为空；");
				continue;
			}
			if (StringUtils.isBlank(r.getDept().getDeptName())) {
				errorMsg.append("第【" + index + "】行部门为空；");
				continue;
			}
			
			String deptName = r.getDept().getDeptName();
			r.setDept(deptMap.get(deptName));
			if (r.getDept() == null) {
				errorMsg.append("第【" + index + "】行部门名称【" + deptName + "】错误；");
				continue;
			}
			
			deptName = r.getDept().getDeptName();
			if (khzDeptMap.get(deptName) == null) {
				errorMsg.append("第【" + index + "】行部门【" + deptName + "】不在对应考核组内；");
				continue;
			}
			
			if (StringUtils.isAnyBlank(r.getXh(), r.getFz(), r.getNr(), r.getFs())) {
				errorMsg.append("第【" + index + "】行xh, fz, nr,fs为空；");
				continue;
			}
			
			/***
			if (!r.getFz().contains("分")) {
				throw new RuntimeException("error fz, " + index);
			}
			**/
			
			r.setKhz(khz);
			r.setType(type);
			importList.add(r);
		}
		
		if (errorMsg.length() > 0) {
			throw new RuntimeException("导入报错：" + errorMsg.toString());
		}
		
		/**
		// 根据考核序号进行合并
		Map<String, Rule> ruleMap = new HashMap<String, Rule>();
		Iterator<Rule> it = importList.iterator();
		while (it.hasNext()) {
			Rule rule = it.next();
			String key = rule.getXh();
			if (!ruleMap.containsKey(key)) {
				ruleMap.put(key, rule);
				continue;
			} else {
				Rule exists = ruleMap.get(key);
				if (rule.getLb().equals(exists.getLb())
						&& rule.getDept().getDeptId().equals(exists.getDept().getDeptId())
						&& rule.getFz().equals(exists.getFz())) {
					exists.setNr(exists.getNr() + rule.getNr());
					if (!exists.getXm().contains(rule.getXm())) {
						exists.setXm(exists.getXm() + rule.getXm());
					}
					it.remove();
				} else {
					throw new RuntimeException("error nr, xh=" + key);
				}
			}
		}
		**/

		this.ruleService.batchSave(importList);

		return AjaxResult.success("导入成功，" + importList.size());
	}
}